package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.widget.BookCoverView;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryEnterpriseZoneBookIndexAction;
import com.tgx.tina.android.task.ATaskService;

import java.util.ArrayList;
import java.util.List;

import logic.bean.BookBlock;
import logic.bean.BookInfo;

/**
 * 员工必读 --> 企业书架
 * @author 刘宾  
 * @date 2014年8月22日 上午9:49:58
 */
public class EnterpriseShelfColumn
        extends
        BaseBusinessActivity
{
	
	private TextView        tvTitle;
	private Button          btnBack;
	private ListView        lv;
	private Context         context;
	private BlockAdapter    blockAdapter;
	private List<BookBlock> bookBlocks = new ArrayList<BookBlock>();
	
	private View						   loadingView;
	private	ImageView					   loadingImg;
	private AnimationDrawable 			   animationDrawable;
	@SuppressLint ("HandlerLeak")
    private Handler handler = new Handler()
	                        {
		                        public void handleMessage(android.os.Message msg) {
			                        switch (msg.what) {
										case 1:
											updateLoadingView(1);
											blockAdapter.notifyDataSetChanged();
											break;
										case -1:
											updateLoadingView(-1);
											break;
									}

								};
	                        };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAService = new ATaskService();
		mAService.startAService(this);
		context = this;
		findViews();
		updateLoadingView(0);
		new QryEnterpriseZoneBookIndexAction(this, new GetEmployeesSubAction()).start();
	}

	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    if(mAService!=null){
			mAService.stopAService();
		}
	}
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	private void findViews() {
		setContentView(R.layout.enterprise_shelf_column);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText(getResources().getString(R.string.enterprise_shelf));
		loadingView = findViewById(R.id.common_loading_layout);
		loadingImg = (ImageView) findViewById(R.id.common_loading__img);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		lv = (ListView) findViewById(R.id.enterprise_shelf_column_listview);
		blockAdapter = new BlockAdapter();
		lv.setAdapter(blockAdapter);
	}
	
	public void goColumnDetailActivity(BookBlock block) {
		Intent intent = new Intent(this, ColumnDetailActivity.class);
		intent.putExtra("blockId", block.getBlockId());
		intent.putExtra("blockTypeId", block.getBlockTypeId());
		intent.putExtra("blockTypeName", block.getBlockTypeName());
		startActivity(intent);
	}
	
	public void goBookDetailActivity(BookInfo bean) {
		//#ifdef SHOW_OLDBOOKDETAIL
		//$ Intent intent = new Intent(this, BookDetailActivity.class);
		//#else
		Intent intent = new Intent(this, NewBookDetailActivity.class);
		//#endif
		intent.putExtra("BookInfo", bean);
		startActivity(intent);
	}
	
	/**
	 * @param flag 0:加载中，1：加载完成，-1：加载失败
	 */
	private void updateLoadingView(int flag){
		switch(flag){
			case -1:
				loadingView.setVisibility(View.VISIBLE);
				lv.setVisibility(View.GONE);
				if(animationDrawable!=null && animationDrawable.isRunning()){
					animationDrawable.stop();
				}
				loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
				break;
			case 0:
				loadingView.setVisibility(View.VISIBLE);
				lv.setVisibility(View.GONE);
				loadingImg.setBackgroundResource(R.drawable.home_progress);
				animationDrawable = (AnimationDrawable) loadingImg.getBackground();
		        animationDrawable.start();
				break;
			case 1:
				loadingView.setVisibility(View.GONE);
				lv.setVisibility(View.VISIBLE);
				break;
		}
	}
	
	private class GetEmployeesSubAction
	        extends
	        BaseAction
	{
		@SuppressWarnings ("unchecked")
        @Override
		public void OK(Object obj) {
			if (obj == null) return;
			bookBlocks = (List<BookBlock>) obj;
			System.out.println("----bookBlocks:" + bookBlocks.toString());
			getUIHandler().sendEmptyMessage(1);
		}
		@Override
		protected void onError() {
		    super.onError();
		    getUIHandler().sendEmptyMessage(-1);
		}
	}
	
	private class BlockAdapter
	        extends
	        BaseAdapter
	{
		ViewHolder holder;

		@Override
		public int getCount() {
			return bookBlocks.size();
		}

		@Override
		public Object getItem(int position) {
			return bookBlocks.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final BookBlock block = (BookBlock) getItem(position);
			final List<BookInfo> data = block.getBookInfos();
			if (view == null)
			{
				holder = new ViewHolder();
				view = LayoutInflater.from(context).inflate(R.layout.enterprise_item, null);
				holder.title = (TextView) view.findViewById(R.id.enterprise_item_title);
				holder.name = (TextView) view.findViewById(R.id.common_book_item_name);
				holder.author = (TextView) view.findViewById(R.id.common_book_item_author);
				holder.intro = (TextView) view.findViewById(R.id.common_book_item_intro);
				holder.cover = (BookCoverView) view.findViewById(R.id.common_book_item_cover);
//				holder.cover = (SmartImageView) view.findViewById(R.id.common_book_item_cover);
				holder.typeImg = (ImageView) view.findViewById(R.id.common_book_item_type_img);
				holder.subLv = (MyListView) view.findViewById(R.id.enterprise_item_listview);
				holder.bookView = view.findViewById(R.id.enterprise_item_body);
				holder.more = view.findViewById(R.id.enterprise_item_more_layout);
				view.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) view.getTag();
			}
			holder.title.setText(block.getBlockTypeName());
			if (data == null || data.isEmpty())
			{
				holder.bookView.setVisibility(View.GONE);
				return view;
			}else{
				final BookInfo b = data.get(0);
				holder.more.setVisibility((data!=null && data.size()>4) ? View.VISIBLE:View.GONE);
				holder.cover.setImageUrl(b.getLogoUrl(),b.getCoverTagPicUrl());
//				holder.cover.setImageUrl(b.getLogoUrl());
				holder.name.setText(TextUtils.isEmpty(b.getEditorRecommend()) ? b.getName() : b.getEditorRecommend());
				holder.author.setText("作者：" + b.getAuthor());
				holder.intro.setText(b.getShortIntro());
				setBookTypeIcon(holder.typeImg, b.getContent_type());

				SubAdapter subAdapter = new SubAdapter();
				subAdapter.setData(data);
				holder.more.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0) {
						goColumnDetailActivity(block);
					}
				});
				holder.bookView.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0) {
						goBookDetailActivity(b);
					}
				});
				holder.subLv.setAdapter(subAdapter);
				holder.subLv.setOnItemClickListener(new SubListViewItemClick());
			}
			return view;
		}
	}
	
	private class ViewHolder
	{
		View           bookView, more;
		TextView       title, name, author, intro;
		ImageView      typeImg;
		BookCoverView cover;
//		SmartImageView cover;
		MyListView     subLv;
	}
	
	private class SubListViewItemClick
	        implements
	        OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
			Object obj = arg0.getAdapter().getItem(arg2);
			if (obj != null && obj instanceof BookInfo)
			{
				goBookDetailActivity((BookInfo) obj);
			}
		}
	}
	
	private class SubViewHolder
	{
		TextView  tag, name, intro;
		ImageView typeImg;
	}
	
	private class SubAdapter
	        extends
	        BaseAdapter
	{
		SubViewHolder          holder;
		private List<BookInfo> data;

		public void setData(List<BookInfo> data) {
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size() > 3 ? 3 : data.size() - 1;
		}

		@Override
		public Object getItem(int position) {
			return data.get(position + 1);
		}

		@Override
		public long getItemId(int position) {
			return position + 1;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			BookInfo b = (BookInfo) getItem(position);
			if (view == null)
			{
				holder = new SubViewHolder();
				view = LayoutInflater.from(context).inflate(R.layout.boutique_sub_item, null);
				holder.tag = (TextView) view.findViewById(R.id.boutique_sub_item_tag);
				holder.name = (TextView) view.findViewById(R.id.boutique_sub_item_name);
				holder.intro = (TextView) view.findViewById(R.id.boutique_sub_item_intro);
				holder.typeImg = (ImageView) view.findViewById(R.id.boutique_sub_item_music_img);
				view.setTag(holder);
			}
			else
			{
				holder = (SubViewHolder) view.getTag();
			}
			holder.tag.setText(b.getTagName());
			holder.name.setText(b.getName());
			holder.intro.setText(b.getShortIntro());
			setBookTypeIcon(holder.typeImg, b.getContent_type());
			return view;
		}
	}
}
